import { readFileSync } from "fs"
import type { Plugin } from "vite"
import type { TransformResult } from "rollup"

/**
 * @author 微若蜉蝣
 * @@description 处理项目中导入的 markdown 文件
 */

export default function (): Plugin {
  const mdRegex = /\.md$/
  const numberRegex = /\d+/

  return {
    name: "vite-plugin-md",
    enforce: "pre",
    transform(code, src): TransformResult {
      if (mdRegex.test(src)) {
        return {
          code: `export default ${JSON.stringify(readFileSync(src, "utf8"))}`,
          map: null,
        }
      }
    },
    async handleHotUpdate(ctx) {
      const { server } = ctx
      if (mdRegex.test(ctx.file)) {
        const defaultRead = ctx.read
        ctx.read = async function () {
          return `export default ${await defaultRead()}`
        }
        const id = numberRegex.exec(ctx.file)[0]
        server.ws.send({
          type: "custom",
          event: "article-update",
          data: {
            id,
            data: await defaultRead(),
          },
        })
        return []
      }
    },
  }
}
